<template>
  <div>
    <el-container>
      <el-header height="70px">
        <p class="header_title">商品类型管理</p>
        <!--  -->
        <el-breadcrumb separator="/">
          <el-breadcrumb-item>商品维护</el-breadcrumb-item>
          <el-breadcrumb-item>商品类型管理</el-breadcrumb-item>
          <el-breadcrumb-item></el-breadcrumb-item>
        </el-breadcrumb>
      </el-header>

      <el-main>
        <el-card class="box-card">
          <div slot="header">
            <span>商品类型列表</span>
            <span style="float: right;">
              <i class="el-icon-arrow-up"></i>
              <i class="el-icon-close"></i>
            </span>
          </div>

          <el-row :gutter="20">
            <el-col :span="4">
              <el-button
                type="primary"
                class="add"
                @click="addDialogVisible = true"
                >添加</el-button>
            </el-col>
            <el-col :span="10">
                <b class="sum_data">数据总数：</b>
               <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="pagination.pagenum"
                :page-size="pagination.pagesize"
                 :page-sizes="[3, 5, 10, 20]"
                layout="total, sizes,prev, pager, next"
                :total="pagination.total"
                class="top_nav">
               </el-pagination>
            </el-col>
          </el-row>

          <!-- 表格 -->
          <el-table :data="goodslist" style="width: 100%" border stripe>
            <el-table-column prop="typeName" label="商品类型名">
            </el-table-column>
            <el-table-column prop="parentType" label="父级类型">
            </el-table-column>
            <el-table-column prop="cover" label="封面">
              <template slot-scope="scope">
                <el-image
                  :src="scope.row.cover"
                  style="width:50px;height:50px"
                  fit="cover"
                ></el-image>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" size="mini" @click="showEditDialog(scope.row)"
                  >编辑</el-button
                >
                <el-button type="danger" size="mini" @click="removeId(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 导航条 -->
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pagination.pagenum"
            :page-size="pagination.pagesize"
            background
            layout="prev, pager, next,total"
            :total="pagination.total"
          >
          </el-pagination>
        </el-card>
      </el-main>
    </el-container>

    <!-- 添加商品对话框 -->
    <el-dialog
      title="添加商品类型"
      :visible.sync="addDialogVisible"
      width="60%"
      @close="addDialogClosed">
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="70px"
        class="demo-ruleForm"
      >
        <el-row :gutter="10">
          <el-col :span="10">
            <el-form-item label="商品类型" prop="typeName">
              <el-input
                v-model="addForm.typeName"
                type="text"
                placeholder="输入商品类型名称"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="父级类型" prop="parentType">
              <el-input type="text" v-model="addForm.parentType"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="封面" prop="cover">
              <el-input type="text" v-model="addForm.cover"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item prop="file">
          <div class="pictitle">
            <b>上传头像</b>(请上传文件大小不超过1MB的正方形图片)
          </div>
          <!-- 头像文件上传 -->
          <el-upload
            class="avatar-uploader"
            ref="upload"
            action="#"
            :show-file-list="false"
            :multiple="false"
            :auto-upload="false"
            :on-change="imgSaveToUrl"
          >
            <img v-if="this.addForm.cover" :src="this.addForm.cover" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑 -->
    <!-- 编辑对话框 -->
    <el-dialog
      title="编辑商品类型"
      :visible.sync="editDialogVisible"
      width="60%"
      @close="editDialogClosed">
      <el-form
        :model="editlist"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="70px"
      >
        <el-form-item label="父级类型" prop="parentType">
          <el-input v-model="editlist.parentType" type="text"></el-input>
        </el-form-item>
        <el-form-item label="商品名" prop="typeName">
          <el-input v-model="editlist.typeName" placeholder="商品类型名"></el-input>
        </el-form-item>
        <el-form-item label="封面" prop="cover">
          <el-image :src="editlist.cover" v-model="editlist.cover"></el-image>
        </el-form-item>
        <el-form-item prop="file">
          <div class="pictitle">
            <b>上传头像</b>(请上传文件大小不超过1MB的正方形图片)
          </div>
          <el-upload
            class="avatar-uploader"
            ref="upload"
            action="#"
            :show-file-list="false"
            :multiple="false"
            :auto-upload="false"
            :on-change="imgSaveToUrl"
          >
            <img v-if="editlist.cover" :src="editlist.cover" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editActionInfo">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
export default {
  data() {
    return {
      goodsInfo: {
        product_types: "",
        total: 2,
      },
      goodslist: [],
      pagination: {
        pagenum: 1,
        pagesize: 3,
        total: 4,
      },
      pagelist: [],
      addDialogVisible: false,
      addForm: {
        cover: "",
        date: "",
        id: "",
        parentType: "",
        typeName: "",
      },
        file: "",
      addFormRules: [],
      editDialogVisible: false,
      editForm: {
        cover: "",
        date: "",
        id: "",
        parentType: "",
        typeName: "",
        file: "",
      },
      editFormRules: {
        typeName: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
        parentType: [
          { required: true, message: "请选择商品类型", trigger: "blur" },
        ],
      },
      editlist: [],
    };
  },
  methods: {
    async getGoodsList() {
      const res = await this.http.get("/type/select", this.pagination);
      console.log(res);
      this.goodslist = res.product_types;
      this.pagination.total = res.total;
      console.log(res);
    },
    // 监听pagesize的改变
    handleSizeChange(newSize) {
      this.pagination.pagesize = newSize;
      this.getGoodsList();
    },
    // 监听 页码值 改变
    handleCurrentChange(newPage) {
      this.pagination.pagenum = newPage;
      this.getGoodsList();
    },
    // 监听增添行为对话框的关闭事件
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    onSubmit() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return;
        // 发起添加网络请求
        const { res } = await this.http.post("/type/add", this.addForm);
        if (status !== 400) {
          this.$message.error("添加商品失败");
        }
        console.log(res);
        this.$message.success("添加商品成功");
        this.addDialogVisible = false;
        this.getGoodsList();
      });
    },
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    //图片上传
    async imgSaveToUrl(event) {
      if (this.beforeUploadPicture(event.raw)) {
        var formData = new FormData();
        formData.append("file", event.raw);
        console.log(formData);
        this.http.upload("/type/upload", formData).then((res) => {
          if (res.code == 200) {
            this.addForm.cover = res.data
            this.editlist.cover = res.data
            console.log(this.addForm);
            this.$message.success("上传成功");
          }
        });
      }
    },
    // 图片上传之前
    beforeUploadPicture(file) {
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isLt10M = file.size / 1024 / 1024 < 10;

      if (!isJPG && !isPNG) {
        this.$message.error("上传头像图片只能是 JPG 或者 PNG 格式!");
      }
      if (isJPG && isPNG) {
        if (!isLt10M) {
          this.$message.error("上传头像图片大小不能超过 10MB!");
        }
      }

      return (isJPG || isPNG) && isLt10M;
    },
    async showEditDialog(row) {
      const res = await this.http.post("/type/update", this.editForm);

      console.log("---showedit-----");
      console.log(res);
      this.editlist = row;
      this.editDialogVisible = true;
    },
    // 监听编辑对话框关闭事件
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },
    // 是否完成编辑行为信息
    editActionInfo() {
      this.$refs.editFormRef.validate(async (valid) => {
        console.log(valid);
        if (!valid) return;
        // 发起修改信息的信息的数据请求
        const res = await this.http.post("/product/update", this.editlist);
        console.log(res);
        // 关闭对话框
        this.editDialogVisible = false;
        // 刷新数据列表
        this.getGoodsList();
        // 提交修改成功
        this.$message.success("更新行为信息成功");
      });
    },
    async removeId(row){
      console.log(row);
      const confirmResult = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((error) => error);
      console.log(confirmResult);
      if (confirmResult !== "confirm") {
        return this.$message.info("已取消删除");
      }

      const res = await this.http.post("/type/delete",row.id);
      console.log(res);
      this.getGoodsList();
    }
  },
  created() {
    this.getGoodsList();
  },
};
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  border: 2px dashed #dedede;
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
